package com.well.register.event.job;

import com.alibaba.fastjson.JSONObject;
import com.well.register.console.service.JobExecutorService;
import com.well.register.console.service.JobService;
import com.well.register.event.AppEvent;
import com.well.register.event.ServerHandler;
import com.well.register.event.job.WellJobRunner;
import com.well.register.util.ThreadUtils;
import com.well.rpc.model.EventType;
import com.well.rpc.model.JobHandlerModel;
import com.well.rpc.model.RegisterModel;
import com.well.rpc.model.TransData;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * <p>
 * Register Job Event
 * </p>
 *
 * @author weedo
 * @since 2022/8/6
 */

@Slf4j
@Component
public class RegisterJobEvent implements AppEvent {
    @Resource
    private JobService jobService;

    @Resource
    private JobExecutorService jobExecutorService;

    @Override
    public synchronized void doEvent(ChannelHandlerContext channelHandlerContext, TransData transData) {
        RegisterModel registerModel = ServerHandler.channelRegisterModel(channelHandlerContext);
        log.info(transData.getJsonData());
        List<JobHandlerModel> jobHandlerModels = getJobHandlerModels(transData);
        jobHandlerModels.forEach((model) -> {
            registerJob(registerModel, model);
        });
    }

    public void registerJob(RegisterModel registerModel, JobHandlerModel model) {
        if (ServerHandler.getScheduledFuture(registerModel, model.getJobName()) == null) {
            //1. 将任务保存到数据库
            jobService.saveJob(model, registerModel);
            //2. 将任务放入Task执行器中
            WellJobRunner runner = new WellJobRunner(registerModel, model.getJobName(), 1, jobExecutorService);
            CronTrigger trigger = new CronTrigger(model.getCron());
            ScheduledFuture<?> schedule = ThreadUtils.schedule(runner, trigger);
            ServerHandler.saveScheduledFuture(schedule, registerModel, model.getJobName());
        }
        log.info("Register Job Success.");
    }

    @Override
    public EventType eventType() {
        return EventType.REGISTER_JOB;
    }


    private List<JobHandlerModel> getJobHandlerModels(TransData transData) {
        return JSONObject.parseArray(transData.getJsonData(), JobHandlerModel.class);
    }
}
